﻿using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;

namespace Cms.Application.Admin.Presenters
{
    public class UpdatePresenter : BasePresenter
    {
        private readonly IUpdateView _view;

        public IUpdater Updater;
        private readonly Administrator _administrator;

        public UpdatePresenter(IUpdateView view)
            : this(view, new RepositoryFactory())
        {
            Updater = new Updater();
        }

        public UpdatePresenter(IUpdateView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.Update)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
        }
        
        public void CheckLatestVersion()
        {
            Version latestVersion = Updater.GetLatestVersion();
            if (latestVersion == null)
                _view.DisplayServiceUnavailableAlert();
            else if (latestVersion.IsGreaterThan(Updater.GetCurrentVersion()))
                _view.DisplayUpdate(latestVersion.Full);
            else
                _view.DisplaySystemIsUpToDateMessage();
        }
    }
}